import { IAssemblyDocTreeNode } from '@amcax/base';
import { convertMatrixBack } from '@amcax/renderer';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { ctx2 } from '@app-cad/module';
import { Matrix4 } from 'three-legacy';
import { FormData } from './types';

export async function copyPart(
  part: IAssemblyDocTreeNode,
  docTree: IAssemblyDocTreeNode,
): Promise<IAssemblyDocTreeNode> {
  if (!part) {
    return null;
  }

  let newAddedDocKey: string;

  try {
    [newAddedDocKey] = await ctx2.commandCenters.basicCommands.copyObject(
      part.key,
    );

    if (!newAddedDocKey) {
      return null;
    }
  } catch (error) {
    MessageTip.error(`命令执行失败：${(error as any).message}`);
    return null;
  }

  return await new Promise((resolve) => {
    function checkPart() {
      const part = docTree.children.find(({ key }) => key === newAddedDocKey);
      if (part) {
        resolve(part);
      } else {
        requestAnimationFrame(checkPart);
      }
    }

    checkPart();
  });
}

export async function transformPart(
  part: IAssemblyDocTreeNode,
  formData: FormData,
  matrix: Matrix4,
) {
  if (!part) {
    return;
  }

  if (formData.distance || formData.angle) {
    try {
      await ctx2.commandCenters.assemblyCommands.transform(
        part.key,
        convertMatrixBack(matrix),
      );
    } catch (error) {
      MessageTip.error(`命令执行失败：${(error as any).message}`);
    }
  }
}
